/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package com.synjones.zeuscloudserver.util.encrypt;

/*
 * @author hubin
 * utilities for byte operation
*/
public final class ByteUtil
{
	private static final char[] _hexChars =
	{
		'0', '1', '2', '3', '4', '5', '6', '7', 
		'8', '9', 'a', 'b', 'c', 'd', 'e', 'f'
	};
	
    /* convert char to hex
     * Example: 'a' ---> 0x10
    */
    public static byte char2Hex(char c)
    {
        c = Character.toLowerCase(c);
        if (c >= '0' && c <= '9')
            return ((byte)(c - '0'));
        else if (c >= 'a' && c <= 'f')
            return ((byte)(c - 'a' + 10));
        return 0;
    }
    
    /*
    * convert hex to char
    * Example: 0x10 --> 'a'
	* and lower is default
    */
    public static char hex2Char(byte b)
    {
		// lower case
        return hex2Char( b, true);
    }
	
    public static char hex2Char(byte b, boolean isLower )
    {
		b = (byte) (b & 0x0f);
		char c = _hexChars[b&0x0f];
		
		if( !isLower )
			c = Character.toUpperCase(c);
		return c;
    }
    
	/*
	* byte array to BCD string
	* example :
	*	0x01 0x02 0x23 ---> "010223"
	*/
    public static String toBcdString(byte[] bytes)
    {
        return toBcdString(bytes, true);
    }
    
	/*
	*
	*/
	public static String toBcdString(byte[] bytes, boolean isLower)
	{
		if (bytes == null || bytes.length == 0)
		{
			return "";
		}

		StringBuilder sb = new StringBuilder();

		for (byte b : bytes)
		{
			sb.append(hex2Char((byte) ((b >> 4) & 0x0f), isLower))
				.append(hex2Char((byte) (b & 0x0f), isLower));
		}
		return sb.toString();
	}
	
	/*
	* bcd string to byte array
	* "010203" ---> 0x01 0x02 0x03
	*/
	public static byte[] fromBcdString(String bcdStr)
	{
		if (bcdStr == null || bcdStr.isEmpty())
			return new byte[] { };
		char[] c = bcdStr.toCharArray();
		
		// in normal, length of bcdStr should be even number
		// otherwise,i will add 0x00 in end
		byte[] b = new byte[c.length / 2 + c.length % 2];

		for (int i = 0; i < b.length; i++)
		{
			b[i] = (byte)((char2Hex(c[i * 2]) << 4) & 0xf0);
			b[i] |= (i * 2 + 1 < c.length) ? (byte)(char2Hex(c[i * 2 + 1]) & 0x0f) : (byte)0;
		}
		return b;
	}
	
	/*
	* check two byte array are equal or not
	*/
	public static boolean equal(byte[] src, byte[] dest)
	{
		if (src == null && dest == null)
			return true;
		if (src == null || dest == null || src.length != dest.length)
			return false;

		for (int i = 0; i < dest.length; i++)
		{
			if (src[i] != dest[i])
				return false;
		}
		return true;
	}
}
